'use strict';
const db = uniCloud.database()
const userDb = db.collection('user')
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('---addUser----event : ', event)
	// let addUserRes = await userDb.add(event)
	 try {
	    const { username, password } = event;
	    
	    if (
	      !username || 
	      typeof username !== 'string' || 
	      !/^[\u4e00-\u9fa5a-zA-Z0-9]{2,16}$/.test(username.trim())
	    ) {
	      return { code: 400, message: '用户名应为2-16位汉字/字母/数字' };
	    }
	    if (!password || typeof password !== 'string' || password.length < 6) {
	      return { code: 400, message: '密码至少6位' };
	    }
	    // 检查用户名是否已存在
	    const existingUser = await userDb.where({ username }).get();
	    if (existingUser.data.length > 0) {
	      return { code: 201, message: '用户名已被注册' };
	    }
	    const encryptedPassword = password; 
	    // 插入用户数据
	    const addUserRes = await userDb.add({
	      username,
	      password: encryptedPassword,
	       createTime: new Date() 
	    });
	//返回数据
	return {
	      code: 200,
	      message: '注册成功',
	      data: {
	        userId: addUserRes.id,
	        username // 返回用户名给前端
	      }
	    };
	  } catch (error) {
	    //异常提示
	    console.error('注册失败：', error);
	    return { code: 500, message: '服务器异常，请稍后重试' };
	  }
};
